<script setup>
import utils from '@/utils/utils'
import { getCurrentInstance, ref, reactive, onMounted, toRaw } from 'vue'
import tree from './component/tree.vue'
import * as XLSX from 'xlsx'
//   获取Composition API 上下文对象
const { ctx } = getCurrentInstance()
// 获取全局挂载的属性
const { $api, $message } =
  getCurrentInstance().appContext.config.globalProperties
// 初始化用户表单对象 reactive 一般创建引用类型
const user = reactive({
  // 用户状态:默认值所有人
  state: 0
})

// const loading = ref(true)

// 选中用户列表对象的ID
const checkedUserIds = ref([])

// 初始化分页对象
const pager = reactive({
  pageNum: 1,
  pageSize: 10
})

// 初始化用户列表用户数据
const userList = ref([])

// 所有角色列表
const roleList = ref([])

// 所有部门列表
const deptList = ref([])
// const treeProps = reactive({
//   children: 'children',
//   label: 'deptName'
// })

// 定义用户操作行为
const action = ref('add')

// 初始化接口调用
onMounted(() => {
  getUserList()
  getDeptList()
  getRoleAllList()
})

// 获取用户列表
const getUserList = async () => {
  // 以对象形式合并user和pager的数据
  let params = { ...user, ...pager }
  try {
    const { list, page } = await $api.getUserList(params)
    // console.log(list)
    userList.value = list
    pager.total = page.total
  } catch (error) {
    console.log(error)
  }
}

// 获取部门列表
const getDeptList = async () => {
  let list = await $api.getDeptList()
  deptList.value = list
  console.log(deptList.value)
}

// 获取权限列表
const getRoleAllList = async () => {
  let list = await $api.getRoleAllList()
  roleList.value = list
}

// 查询事件，获取用户列表
const handleQuery = () => {
  getUserList()
}

// 分页事件处理
const handleCurrentChange = (currentPage) => {
  // 当前的页码传回去
  pager.pageNum = currentPage
  // 获取当前页的数据
  getUserList()
}

// 重置查询表单
const handleReset = (form) => {
  ctx.$refs[form].resetFields()
}

// 用户单个删除
const handleDel = async (row) => {
  console.log(row.userId)
  const res = await $api.userDel({
    userIds: [row.userId] //可单个删除,也可批量删除
  })
  console.log(res)
  $message.success('删除成功!')
  getUserList()
}

// 多选框赋值
const handleSelectionChange = (list) => {
  let arr = []
  list.map((item) => {
    arr.push(item.userId)
  })
  // console.log(arr)
  checkedUserIds.value = arr
}

// 批量删除
const handlePatchDel = async () => {
  if (checkedUserIds.value.length == 0) {
    $message.error('请选择要删除的用户!')
    return
  }
  const res = await $api.userDel({
    userIds: checkedUserIds.value //可单个删除,也可批量删除
  })
  if (res.nModified > 0) {
    $message.success('删除成功!')
    // 刷新列表
    getUserList()
  } else {
    $message.success('修改失败!')
  }
}

// 设置弹窗初始值
const outerVisible = ref(false)

// 弹窗打开
const handleCreate = () => {
  action.value = 'add'
  outerVisible.value = true
}

// 新增用户数据
const userForm = reactive({
  userName: '',
  userEmail: '',
  mobile: '',
  job: '',
  state: '',
  roleList: '',
  deptName: ''
})

// 弹窗关闭
const handleClose = () => {
  outerVisible.value = false
  handleReset('dialogForm')
}

// 用户提交
const handleSubmit = () => {
  ctx.$refs.dialogForm.validate(async (valid) => {
    if (valid) {
      // toRaw 从Reactive或Ref中得到原始数据  作用: 做一些不想被监听的事情(提升性能)
      let params = toRaw(userForm)
      params.userEmail += '@imooc.com'
      params.action = action.value
      let res = await $api.userSubmit(params)
      console.log(res)
      outerVisible.value = false
      $message.success('用户创建成功!')
      getUserList()
    }
  })
}

// 用户编辑
const handleEdit = (row) => {
  console.log(row)
  action.value = 'edit'
  outerVisible.value = true
  ctx.$nextTick(() => {
    // 将row的数据赋值到userForm
    Object.assign(userForm, row)
  })
}

// 定义动态表格-格式
const columns = reactive([
  {
    label: '用户ID',
    prop: 'userId',
    width: 100
  },
  {
    label: '用户名',
    prop: 'userName',
    width: 100
  },
  {
    label: '岗位',
    prop: 'job',
    width: 120
  },
  {
    label: '用户角色',
    prop: 'role',
    formatter(row, column, value) {
      // console.log(row, column, value)
      return {
        0: '管理层',
        1: '员工'
      }[value]
    },
    width: 120
  },
  {
    label: '用户状态',
    prop: 'state',
    formatter(row, column, value) {
      return {
        1: '在职',
        2: '离职',
        3: '试用期'
      }[value]
    },
    width: 120
  },

  {
    label: '邮箱',
    prop: 'userEmail'
  },
  {
    label: '登录时间',
    prop: 'lastLoginTime',
    width: 180,
    formatter: (row, column, value) => {
      return utils.formateDate(new Date(value))
    }
  }
])

// 定义表单校验规则
const rules = reactive({
  userName: [{ required: true, message: '请输入用户名称', trigger: 'blur' }],
  userEmail: [{ required: true, message: '请输入用户邮箱', trigger: 'blur' }],
  mobile: [
    {
      pattern: /1[3-9]\d{9/,
      message: '请输入正确的手机号格式',
      trigger: 'blur'
    }
  ],
  deptId: [
    {
      required: true,
      message: '请输入用户名称',
      trigger: 'blur'
    }
  ]
})

const list = [
  ['用户ID', '用户名', '职位', '用户角色', '用户状态', '邮箱', '注册时间']
]
// 定义表格导出
const handleExportXlsx = () => {
  userList.value.map((item, i) => {
    const arr = [i + 1]
    arr.push(
      ...[
        item.userId,
        item.userName,
        item.job,
        item.role,
        item.state,
        item.userEmail,
        item.createTime
      ]
    )
    list.push(arr)
  })
  let WorkSheet = XLSX.utils.aoa_to_sheet(list)
  let new_workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(new_workbook, WorkSheet, '第一页')
  XLSX.writeFile(new_workbook, `表格.xlsx`)
}
</script>
<template>
  <div class="userForm">
    <!-- 搜索视图 -->
    <el-card class="box-card">
      <el-form ref="form" :inline="true" class="demo-form-inline" :model="user">
        <el-form-item label="用户ID" prop="userId">
          <el-input placeholder="请输入用户ID" v-model="user.userId" />
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input placeholder="请输入用户名称" v-model="user.userName" />
        </el-form-item>
        <el-form-item label="用户状态" prop="state">
          <el-select v-model="user.state">
            <el-option label="所有" :value="0" />
            <el-option label="在职" :value="1" />
            <el-option label="离职" :value="2" />
            <el-option label="试用期" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" size="default"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button ize="default" @click="handleReset('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="box-card animate__animated animate__fadeInLeft">
      <el-row>
        <el-col :span="3">
          <tree :deptList="deptList" />
          <!-- <el-tree :data="deptList" :props="treeProps" node-key="_id" @node-click="handleNodeClick"></el-tree> -->
        </el-col>
        <el-col :span="21">
          <el-form :inline="true" class="demo-form-inline action">
            <el-form-item>
              <el-button
                type="primary"
                @click="handleCreate"
                size="default"
                v-has="'user-add'"
                >新增</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-button
                type="danger"
                @click="handlePatchDel"
                size="default"
                v-has="'user-patch-delete'"
                >批量删除</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-button type="success" @click="handleExportXlsx" size="default"
                >导出Excel</el-button
              >
            </el-form-item>
          </el-form>
          <el-table
            key="tableKey"
            ref="sortableList"
            :data="userList"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column
              v-for="item in columns"
              :prop="item.prop"
              :key="item.prop"
              :label="item.label"
              :width="item.width"
              :formatter="item.formatter"
            ></el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button
                  @click="handleEdit(scope.row)"
                  type="primary"
                  link
                  v-has="'user-edit'"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  link
                  v-has="'user-delete'"
                  @click="handleDel(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next,jumper"
          :total="parseInt(pager.total)"
          :page-size="pager.pageSize"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 弹出框 -->
    <el-dialog title="新增用户" v-model="outerVisible" width="50%" height="80%">
      <el-form
        label-width="120px"
        :model="userForm"
        ref="dialogForm"
        :rules="rules"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input
            :disabled="action == 'edit'"
            placeholder="请输入用户名称"
            v-model="userForm.userName"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input
            placeholder="请输入用户邮箱"
            :disabled="action == 'edit'"
            v-model="userForm.userEmail"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="user">
          <el-input placeholder="请输入用户手机号" v-model="userForm.mobile" />
        </el-form-item>
        <el-form-item label="岗位" prop="deptId">
          <el-input v-model="userForm.job" placeholder="请输入用户岗位" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select
            placeholder="请选中状态"
            v-model="userForm.state"
            style="width: 100%"
          >
            <el-option label="在职" :value="1" />
            <el-option label="离职" :value="2" />
            <el-option label="试用期" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="系统角色" prop="roleList">
          <el-select
            v-model="userForm.roleList"
            placeholder="请选择用户系统角色"
            multiple
          >
            <el-option
              v-for="role in roleList"
              :key="role._id"
              :label="role.roleName"
              :value="role._id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门" prop="roleList">
          <el-cascader
            v-model="userForm.deptName"
            placeholder="请选择所属部门"
            :options="deptList"
            :props="{
              checkStrictly: true,
              value: deptName,
              label: 'deptName'
            }"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style lang="scss">
.box-card {
  margin-top: 25px;
}
.pagination {
  margin-top: 1.5rem;
  display: flex;
  justify-content: end;
}
.slide-right-to-left-enter-active,
.slide-right-to-left-leave-active {
  transition: transform 0.5s; /* 过渡效果时长，可以根据需要调整 */
}

.slide-right-to-left-enter,
.slide-right-to-left-leave-to {
  transform: translateX(100%); /* 初始状态和离开时的位置（从右边移入） */
}

/* 仅对第一层级的 el-tree 节点设置 padding */
.el-tree-node__content {
  padding: 15px 0;
}
</style>
